#include "dtwentyitemdelegate.h"


#include <dtwentymodel.h>


#include <QComboBox>


DTwentyItemDelegate::DTwentyItemDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}

QWidget *DTwentyItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QVariant valueType = index.data(DTwentyModel::Role_VALUE_TYPE);
    switch(valueType.toInt())
    {
    case DTwentyModel::ValueType_SELECTION:
        return new QComboBox(parent);

    case DTwentyModel::ValueType_NORMAL:
        break;

    default:
        break;
    }

    return QStyledItemDelegate::createEditor(parent, option, index);
}

void DTwentyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox* cb = qobject_cast<QComboBox*>(editor);
    if (cb)
    {
        QVariantMap options = index.data(DTwentyModel::Role_VALUE_OPTIONS).toMap();
        foreach (QString name, options.keys())
        {
            cb->addItem(name, options.value(name));
        }

        cb->setCurrentText(index.data().toString());
        return;
    }

    QStyledItemDelegate::setEditorData(editor, index);
}

void DTwentyItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox* cb = qobject_cast<QComboBox*>(editor);
    if (cb)
    {
        model->setData(index, cb->itemData(cb->currentIndex()), DTwentyModel::Role_VALUE_OPTIONS);
        return;
    }

    QStyledItemDelegate::setModelData(editor, model, index);
}
